package com.qclix.inv.webservice;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * Servlet that serves XSD files available only on the classpath.
 * The configuration is based on an internal static map <bold>request URI --&gt; resource path</bold>  
 */
public class XsdServlet extends HttpServlet {

    private static final Map<String,String> PATH_RESOURCE_MAP;
    private static final String NO_SUCH_XSD_MSG = "" +
            "<!DOCTYPE html SYSTEM \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" +
            "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" +
            "    <head>\n" +
            "        <title>Quattroclix XML Schema</title>\n" +
            "    </head>\n" +
            "    <body>\n" +
            "        No such XML Schema !\n" +
            "    </body>\n" +
            "</html>";

    static{
        PATH_RESOURCE_MAP = new HashMap<String,String>();
        PATH_RESOURCE_MAP.put("invoice.xsd", "/invoice.xsd");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String xsd = requestURI.substring(requestURI.lastIndexOf("/") + 1);
        if (! PATH_RESOURCE_MAP.containsKey(xsd)) {
            resp.setContentType("text/html");
            resp.getWriter().write(NO_SUCH_XSD_MSG);
            resp.getWriter().close();
            return;
        }

        InputStream in = this.getClass().getResourceAsStream(PATH_RESOURCE_MAP.get(xsd));
        if (in == null) {
            throw new ServletException("No resource found for valid PATH " + req.getRequestURI());
        }

        resp.setContentType("text/xml");
        
        byte[] buffer = new byte[1024];
        int size;
        OutputStream out = resp.getOutputStream();
        while ((size = in.read(buffer)) > 0) {
            out.write(buffer, 0, size);
        }
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        throw new ServletException("POST is not supported");        
    }
}
